#include "mainwindow.h"
#include "ui_mainwindow.h"

extern void Log(const char* format, ...);

mainwindow::mainwindow(QWidget* parent, Qt::WFlags flags) : QMainWindow(parent, flags)
{
    // Setup the UI
    ui.setupUi(this);

    // Network thread
    NetworkThread = new nThread;

    // Start the network thread with normal priority
    NetworkThread->start(QThread::NormalPriority);

    // File -> Exit
    connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));

    // Login button
    connect(ui.Login, SIGNAL(clicked()), this, SLOT(Login()));
}

mainwindow::~mainwindow()
{
    if(NetworkThread) delete NetworkThread;
}

void mainwindow::closeEvent(QCloseEvent* event)
{
    if(QMessageBox::warning(this, "Close Confirmation", "Are you sure you want to close phClientless?\nDoing so will disconnect any connected character.", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
    {
        NetworkThread->sSocket->disconnectFromHost();
    }
    else
    {
        event->ignore();
    }
}

void mainwindow::Login()
{
    // Get text from the boxes
    std::string user = ui.Username->text().toStdString();
    std::string pass = ui.Password->text().toStdString();
    std::string server = ui.ServerList->currentText().toStdString();

    // Check the username, password, and server length
    if(user.length() == 0)
    {
        QMessageBox::critical(this, "Username", "You must type your Silkroad username in to continue");
    }
    else if(pass.length() == 0)
    {
        QMessageBox::critical(this, "Password", "You must type your Silkroad username in to continue");
    }
    else if(server.length() == 0)
    {
        QMessageBox::critical(this, "Server", "You must select a server to continue");
    }
    else
    {
        // Star the login process
        NetworkThread->PacketProcessor->Login(user.c_str(), pass.c_str(), server.c_str());
        ui.Login->setEnabled(false);
    }
}

void mainwindow::CharacterSelect()
{

}

void mainwindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui.retranslateUi(this);
        break;
    default:
        break;
    }
}
